import MarkdownIt from 'markdown-it'
import markdownItTable from 'markdown-it-multimd-table'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'
/**
 * Markdown渲染管理
 */
export interface MarkdownOptions {
  html?: boolean
  linkify?: boolean
  typographer?: boolean
  breaks?: boolean
}

export function useMarkdownRender(options: MarkdownOptions = {}) {
  const {
    html = true,
    linkify = true,
    typographer = true,
    breaks = true
  } = options

  const md = new MarkdownIt({
    html,
    linkify,
    typographer,
    breaks,
    highlight: function (str: string, lang: string) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return '<pre class="hljs"><code>' +
            hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
            '</code></pre>'
        } catch (__) {}
      }
      return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>'
    }
  })

  md.use(markdownItTable)

  const renderMarkdown = (text: string): string => {
    if (!text) return ''

    try {
      // 检查代码块是否完整
      const codeBlockCount = (text.match(/```/g) || []).length
      let renderText = text
      if (codeBlockCount % 2 === 1) {
        renderText += '\n```'
      }
      return md.render(renderText)
    } catch (error) {
      return text.replace(/</g, '&lt;').replace(/>/g, '&gt;')
    }
  }

  const highlightCodeBlocks = (element: HTMLElement) => {
    const codeBlocks = element.querySelectorAll('pre code')
    codeBlocks.forEach((block) => {
      if (!block.classList.contains('hljs')) {
        hljs.highlightElement(block as HTMLElement)
      }
    })
  }

  const extractCodeBlocks = (text: string): Array<{lang: string, code: string}> => {
    const blocks: Array<{lang: string, code: string}> = []
    const regex = /```(\w*)\n?([\s\S]*?)\n?```/g
    let match

    while ((match = regex.exec(text)) !== null) {
      blocks.push({
        lang: match[1] || 'text',
        code: match[2].trim()
      })
    }

    return blocks
  }

  return {
    md,
    renderMarkdown,
    highlightCodeBlocks,
    extractCodeBlocks
  }
}
